<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <Layout_top></Layout_top>
            </el-header>
            <el-main>
                <el-table :data="cartItems" @selection-change="handleSelectionChange" ref="tableRef">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="商品图片" width="120">
                        <template #default="scope">
                            <img :src="scope.row.gpic" class="product-image" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="gname" label="商品名称"></el-table-column>
                    <el-table-column label="单价" width="120">
                        <template #default="scope">￥{{ scope.row.price }}</template>
                    </el-table-column>
                    <el-table-column label="数量" width="200">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.number" @change="(val) => {
                    updateTotal();
                    handleQuantityChange(scope.row, val)
                }" :min="1"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" width="120">
                        <template #default="scope">￥{{ (scope.row.price * scope.row.number).toFixed(2) }}</template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template #default="scope">
                            <el-button size="mini" type="danger" @click="removeItem(scope)">删除</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <div class="empty-cart">
                            <el-empty description="购物车空空如也~" />
                        </div>
                    </template>
                </el-table>
                <div class="checkout-section">
                    <el-checkbox v-model="allChecked" @change="selectAll">全选</el-checkbox>
                    <div class="total-price">合计：￥{{ totalPrice.toFixed(2) }}</div>
                    <el-button type="primary" @click="checkout" class="checkout-btn">结算</el-button>
                </div>
            </el-main>
            <el-footer>
                <Layout_foot></Layout_foot>
            </el-footer>
        </el-container>
    </div>
</template>

<script setup>
import Layout_top from '@/components/Layout_top.vue'
import Layout_foot from '@/components/Layout_foot.vue'
import { ref, computed } from 'vue';
import { ElTable, ElTableColumn, ElButton, ElCheckbox, ElContainer, ElHeader, ElMain, ElFooter, ElInputNumber } from 'element-plus';

const cartItems = ref([]);
import { onMounted } from 'vue'
import { getCartListService, updateCartService, deleteCartService } from '@/api/cart.js'
onMounted(async () => {
    let res = await getCartListService();
    cartItems.value = res.data;
})


const selectedItems = ref([]);
const allChecked = ref(false);
const tableRef = ref(null);
const selectedIds = ref([]);
const handleSelectionChange = (selection) => {
    // 获取选中商品的ID数组
    selectedIds.value = selection.map(item => item.id);
    selectedItems.value = selection;
    updateTotal();
    allChecked.value = cartItems.value.length === selectedItems.value.length;
    // console.log(selectedItems.value);
};

// 修改数量输入处理逻辑
const handleQuantityChange = async (goods, newVal) => {
    try {
        await updateCartService(goods.id, newVal);
    } catch (error) {
        ElMessage.error('数量更新失败')
    }
}

const selectAll = (checked) => {
    cartItems.value.forEach(item => {
        tableRef.value.toggleRowSelection(item, checked);
    });
    updateTotal();
};

const removeItem = async (scope) => {
    ElMessageBox.confirm('确定删除？', '温馨提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        // 根据ID删除服务端数据
        await deleteCartService(scope.row.id);

        // 根据ID删除本地数据（不再依赖index）
        const index = cartItems.value.findIndex(item => item.id === scope.row.id);
        if (index > -1) {
            cartItems.value.splice(index, 1);
        }

        // 清除无效的选中状态
        selectedItems.value = selectedItems.value.filter(
            item => item.id !== scope.row.id
        );

        updateTotal();

        // 处理空购物车状态
        if (cartItems.value.length === 0) {
            selectedItems.value = [];
            allChecked.value = false;
        }
    })


};

const totalPrice = computed(() =>
    selectedItems.value.reduce((sum, item) => sum + (item.price * item.number), 0)
);

const updateTotal = () => {
    allChecked.value = cartItems.value.length === selectedItems.value.length;

};

import { ElMessage, ElMessageBox } from 'element-plus';
import { addOrderService } from '@/api/order.js'
const checkout = async () => {
    if (selectedItems.value.length === 0) {
        ElMessage.warning('请选择商品进行结算');
        return;
    }
    ElMessageBox.confirm('确定结算？', '温馨提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        //用户点击了确认
        try {
            let res = await addOrderService({
                selectedCarts: selectedIds.value
            });

            if (res.code === 200) {
                ElMessage.success('结算成功');
                // 清空已结算商品
                cartItems.value = cartItems.value.filter(
                    item => !selectedIds.value.includes(item.id)
                );
                // 重置选中状态
                selectedItems.value = [];
                selectedIds.value = [];

            }
        } catch (error) {
            ElMessage.error('结算失败');
        }
    })


};
</script>

<style lang="scss" scoped>
.common-layout {
    width: 100%;
    margin: auto;
}

.product-image {
    width: 80px;
    height: 80px;
}

.checkout-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.total-price {
    font-size: 18px;
    color: red;
}

.checkout-btn {
    float: right;
}
</style>